package com.uh.calculation.batchOperator;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.uh.calculation.bean.*;
import com.uh.calculation.util.FormulaBatchUtil;
import com.uh.calculation.util.FormulaUtil;
import com.uh.calculation.util.GetBean;
import com.uh.calculation.util.TimeUtil;
import com.uh.microservice.core.dao.JdbcDao;
import lombok.Data;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Data
/**
 * 增速环比计算，即当前字段与上一周期当前字段比较 ，为方便解析，使用配置时加上#m作为上一周期字段的配置
 */
public class ZsBathHuanbiOperator {
    private JdbcDao jdbcDao;

    private WarnJiSuanBean warnJiSuanBean;

    private SqlWriteBean sqlWriteBean;

    public ZsBathHuanbiOperator(JdbcDao jdbcDao, WarnJiSuanBean warnJiSuanBean, SqlWriteBean sqlWriteBean){
        this.jdbcDao=jdbcDao;
        this.warnJiSuanBean=warnJiSuanBean;
        this.sqlWriteBean=  sqlWriteBean;
    }

    public void jisuan(JSONArray ls, List<OperatorVal> list) {
        if (ls == null || ls.size() == 0) {
            return;
        }
        this.warnJiSuanBean = warnJiSuanBean;
        //反转2021 与 2022字段区别
        //GetFileds getFileds = new GetFileds(jdbcDao,list,warnJiSuanBean);
        for (OperatorVal operatorVal : list) {
            List<FormulaBean> formulaBeans = operatorVal.getFormulaBeans();//计算公式
            String field = operatorVal.getField();
            List<TbFeild> tbFeilds = GetBean.getTbf(field);
            String f1 = tbFeilds.get(0).getFieldName();
            String f2 = tbFeilds.get(1).getFieldName();
            Date lastTime = warnJiSuanBean.getLastTime();
            for (int i = 1; i < ls.size(); i++) {
                try {
                    JSONObject object = ls.getJSONObject(i);
                    String timeCode = object.get("time_code").toString();
                    if (TimeUtil.bj(lastTime, timeCode, sqlWriteBean.getYear_is_month(), sqlWriteBean.getIs_hc())) {
                        String val1 = object.get(f1).toString();
                        String val2 = ls.getJSONObject(i-1).get(f2).toString();
                        //根据当前计算类解析规则  将数据和字段对应
                        tbFeilds.get(0).setData(val1);
                        tbFeilds.get(1).setData(val2);
                        //扔进公式解析工具
                        sqlWriteBean.setDimension(operatorVal.getDimension());
                        sqlWriteBean.setTimeCode(timeCode);
                        new FormulaBatchUtil(tbFeilds, formulaBeans, warnJiSuanBean, sqlWriteBean);
                    }
                } catch (Exception e) {
                }
            }
        }
    }
}